$(function() {

    $('body').on('click', '.tree li span', function(e) {

        var notSelected;

        if ($(this).attr("id") === undefined) {
            notSelected = true;
        }

        $(".tree li span").removeAttr("id");

        if (notSelected) {
            $(this).attr("id", "selected");
        }

    });

    $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');

    $(document).on("fragmentChanged", function(data) {
        $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
    });

    $('body').on('click', ".tree li.parent_li > span", function(e) {

        var children = $(this).parent('li.parent_li').find(' > ul > li');

        if (children.is(":visible")) {

            children.hide('fast');

            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');

        } else {
            children.show('fast');
            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
        }

        e.stopPropagation();
    });


});


